import express, { NextFunction, Request, Response } from 'express';
import bcrypt from 'bcryptjs'; // 引入bcryptjs用于密码加密
import jwt from 'jsonwebtoken'; // 引入jsonwebtoken用于生成JWT
import { config } from '../config';
import dbServe from '../db/db';
import { TABLE_NAME } from '../enums';
import { IUser } from '../interfaces';
const router = express.Router();

// 定义路由规则
/**
 * 登录
 */
router.post('/login', async function (req: Request, res: Response, next: NextFunction) {
  try {
    let { username, password } = req.getParams();
    // 查找用户
    const users = await getCurrentUser(username as string);
    if (!users || users.length === 0) {
      res.sendError('用户不存在');
      return;
    }
    const user = users[0];

    // 校验密码
    if (!(await bcrypt.compare(password as string, user.password))) {
      return res.sendError('用户验证失败', 401); // 发送401响应
    }

    // 生成JWT
    const token = jwt.sign({ userId: user.id }, config.jwtSecret, {
      expiresIn: '5d',
    }); // 有效期5天 格式 ${数字}${d|h|m|s}

    res.sendSuccess(token, '登录成功'); // 发送JWT到客户端
  } catch (err) {
    next(err);
  }
});

/**
 * 注册
 */
router.post('/register', async function (req: Request, res: Response, next: NextFunction) {
  try {
    let { username, password } = req.getParams();
    // 查找用户
    const users = await getCurrentUser(username as string);
    if (users && users.length > 0) {
      res.sendError('用户名已存在');
      return;
    }

    const hashedPassword = await bcrypt.hash(password as string, 10); // 对密码进行加密
    const data = { username, password: hashedPassword };
    let result = await dbServe.insertData(TABLE_NAME.USER, data);
    if (result) {
      res.sendSuccess({ username }, '用户注册成功');
    } else {
      res.sendError(`用户注册失败: ${result}`);
    }
  } catch (err: any) {
    next(err);
  }
});
// router.post('/getCurrentUser', userController.getCurrentUser);
// router.get('/getAllUsers', userController.getAllUsers);
// router.post('/updateUser', userController.updateUser);

const getCurrentUser = async (username: string) => {
  return await dbServe.executeQuery<IUser>(`SELECT * FROM ${TABLE_NAME.USER} WHERE username = ?`, [username]);
};

// 导出路由器实例
export default router;
